﻿using NPOI.HSSF.UserModel;
using NPOI.SS.UserModel;
using NPOI.Util;
using NPOI.XSSF.UserModel;
using Quartz.Util;
using SharpCompress.Common;
using System;
using System.Collections.Generic;
using System.Drawing;
using System.Drawing.Imaging;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace Publicuse.Util.Excel
{
    public static class ImageFill
    {
        /// <summary>
        /// 设置图片到单元格
        /// </summary>
        /// <param name="sheet"></param>
        /// <param name="workbook"></param>
        /// <param name="path"></param>
        /// <param name="fileurl"></param>
        /// <param name="row"></param>
        /// <param name="col"></param>
        /// <param name="iscompress"></param>
        /// <param name="msg"></param>
        public static void AddImageToCell(this ISheet sheet, IWorkbook workbook, string path,string fileurl,
            int row, int col, bool iscompress,out string msg)
        {
            var filePath = string.Empty;
            var newfilePath = string.Empty;
            try
            {
                msg=string.Empty;
                if (FileUtil.ExistsDir(path))
                {
                    var sindex = 1;
                    var dx1 = 1;
                    var dx2 = 1;
                    if (fileurl.Split(',').Length == 1)
                    {
                        filePath = string.Empty;
                        filePath = path + fileurl;
                        filePath = filePath.Replace("\\", "/"); // Linux系统部署路径需要改成这样
                        if (!string.IsNullOrEmpty(filePath))
                        {
                            if (iscompress)
                            {
                                //byte[] bytes = System.IO.File.ReadAllBytes(filePath);
                                //var bytes = ImageUtil.CompressionImage(filePath, 5);
                                var filestrlist = filePath.Split('/');
                                List<string> newlist = new List<string>();
                                var sid = 1;
                                foreach (var itemb in filestrlist)
                                {
                                    if (sid == filestrlist.Length)
                                    {
                                        var itemc = itemb.Replace(".", "copy.");
                                        newlist.Add(itemc);
                                    }
                                    else
                                    {
                                        newlist.Add(itemb);
                                    }
                                    sid++;
                                }
                                newfilePath = String.Join("/", newlist);
                                FileUtil.FileCopy(filePath, newfilePath);
                                ImageUtil.Compressexport(newfilePath, newfilePath);
                            }
                            else
                            {
                                newfilePath = filePath;
                            }
                            byte[] bytes = System.IO.File.ReadAllBytes(newfilePath);
                            int pictureIdx = workbook.AddPicture(bytes, NPOI.SS.UserModel.PictureType.JPEG);
                            HSSFPatriarch patriarch = (HSSFPatriarch)sheet.CreateDrawingPatriarch();
                            
                            //设置图片坐标与大小
                            //函数原型：XSSFClientAnchor(int dx1, int dy1, int dx2, int dy2, int col1, int row1, int col2, int row2)；
                            //坐标(col1,row1)表示图片左上角所在单元格的位置，均从0开始，比如(5,2)表示(第六列，第三行),即F3；注意：图片左上角坐标与(col1,row1)单元格左上角坐标重合
                            //坐标(col2,row2)表示图片右下角所在单元格的位置，均从0开始，比如(10,3)表示(第十一列，第四行),即K4；注意：图片右下角坐标与(col2,row2)单元格左上角坐标重合
                            //坐标(dx1,dy1)表示图片左上角在单元格(col1,row1)基础上的偏移量(往右下方偏移)；(dx1，dy1)的最大值为(1023, 255),为一个单元格的大小
                            //坐标(dx2,dy2)表示图片右下角在单元格(col2,row2)基础上的偏移量(往右下方偏移)；(dx2,dy2)的最大值为(1023, 255),为一个单元格的大小
                            HSSFClientAnchor anchor = new HSSFClientAnchor(0, 0, 0, 0, col, row, col + 1, row + 1);
                            HSSFPicture pict = (HSSFPicture)patriarch.CreatePicture(anchor, pictureIdx);
                            if (iscompress)
                            {
                                FileUtil.DelFile(newfilePath);
                            }
                            //自动调节图片大小
                            //pict.Resize();
                        }
                        else
                        {
                            msg = $"当前图片文件目录不存在！";
                        }
                    }
                    else
                    {
                        foreach (var item in fileurl.Split(','))
                        {
                            filePath = string.Empty;
                            newfilePath = string.Empty;
                            filePath = path + item;
                            filePath = filePath.Replace("\\", "/"); // Linux系统部署路径需要改成这样
                            if (!string.IsNullOrEmpty(filePath))
                            {
                                byte[] bytes = System.IO.File.ReadAllBytes(filePath);
                                int pictureIdx = workbook.AddPicture(bytes, NPOI.SS.UserModel.PictureType.PNG);
                                HSSFPatriarch patriarch = (HSSFPatriarch)sheet.CreateDrawingPatriarch();
                                //设置图片坐标与大小
                                //函数原型：XSSFClientAnchor(int dx1, int dy1, int dx2, int dy2, int col1, int row1, int col2, int row2)；
                                //坐标(col1,row1)表示图片左上角所在单元格的位置，均从0开始，比如(5,2)表示(第六列，第三行),即F3；注意：图片左上角坐标与(col1,row1)单元格左上角坐标重合
                                //坐标(col2,row2)表示图片右下角所在单元格的位置，均从0开始，比如(10,3)表示(第十一列，第四行),即K4；注意：图片右下角坐标与(col2,row2)单元格左上角坐标重合
                                //坐标(dx1,dy1)表示图片左上角在单元格(col1,row1)基础上的偏移量(往右下方偏移)；(dx1，dy1)的最大值为(1023, 255),为一个单元格的大小
                                //坐标(dx2,dy2)表示图片右下角在单元格(col2,row2)基础上的偏移量(往右下方偏移)；(dx2,dy2)的最大值为(1023, 255),为一个单元格的大小
                                HSSFClientAnchor anchor = new HSSFClientAnchor(0, 0, 0, 0, col, row, col + 1, row + 1);
                                HSSFPicture pict = (HSSFPicture)patriarch.CreatePicture(anchor, pictureIdx);
                                if (iscompress)
                                {
                                    FileUtil.DelFile(newfilePath);
                                }
                                bytes = null;
                                //自动调节图片大小
                                //pict.Resize();
                            }
                            else
                            {
                                msg = $"当前图片文件目录不存在！";
                            }
                            sindex++;
                        }
                    }                
                }
            }
            catch (Exception ex)
            {
                msg = ex.Message+"|"+ ex.StackTrace;
            }
        }

        public static void AddImageToCellold(this ISheet sheet, IWorkbook workbook, string path, string fileurl, int row, int col, out string msg)
        {
            try
            {
                msg = string.Empty;
                if (FileUtil.ExistsDir(path))
                {
                    var sindex = 1;
                    foreach (var item in fileurl.Split(','))
                    {
                        var FileName = path + item;
                        FileName = FileName.Replace("\\", "/"); // Linux系统部署路径需要改成这样
                        byte[] bytes = System.IO.File.ReadAllBytes(FileName);
                        if (!string.IsNullOrEmpty(FileName))
                        {
                            int pictureIdx = workbook.AddPicture(bytes, NPOI.SS.UserModel.PictureType.JPEG);
                            HSSFPatriarch patriarch = (HSSFPatriarch)sheet.CreateDrawingPatriarch();
                            HSSFClientAnchor anchor = new HSSFClientAnchor(100, 10, 100, 100, col, row, col + 1, row + 1);
                            //##处理照片位置，【图片左上角为（col, row）第row+1行col+1列，右下角为（ col +1, row +1）第 col +1+1行row +1+1列，宽为100，高为50
                            HSSFPicture pict = (HSSFPicture)patriarch.CreatePicture(anchor, pictureIdx);

                            //自动调节图片大小
                            //pict.Resize();
                        }
                        else
                        {
                            msg = $"当前图片文件目录不存在！";
                        }
                        sindex++;
                    }

                }
            }
            catch (Exception ex)
            {
                msg = ex.Message;
            }
        }

    }
}
